<template>
    <div class="app-container orderList">
        <div class="filter-container">
            <el-form ref="queryForm" :inline="true" :model="listQuery" label-position="left" label-width="100px" style="margin-left:30px;">
               <el-form-item :label="$t('articlefiles.keyword')" style="width:40%">
                    <el-input :placeholder="$t('articlefiles.keyword')" v-model="listQuery.keyword" style="width: 350px;" class="filter-item" @keyup.enter.native="handleFilter"/>
                </el-form-item>
                <el-form-item :label="$t('table.package')"  style="width:25%">
                    <el-select v-model="listQuery.group_id" :placeholder="$t('table.package')" clearable style="width: 150px" class="filter-item" >
                        <el-option v-for="(item, index) in groupList" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('articlefiles.status')" style="width:25%">
                    <el-select v-model="listQuery.status" :placeholder="$t('articlefiles.status')" clearable style="width: 150px" class="filter-item" multiple>
                        <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('table.date_in')" style="width:40%">
                    <el-date-picker
                        v-model="listQuery.date_in"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.date_from')"
                        :end-placeholder="$t('placeholder.date_to')"
                        value-format="yyyy-MM-dd hh:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('table.product')" style="width:25%">
                    <el-select v-model="listQuery.product_id" :placeholder="$t('table.product')" clearable style="width: 150px" class="filter-item" multiple>
                        <el-option v-for="(item, index) in productOptions" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('table.order_type')" style="width:25%">
                    <el-select v-model="listQuery.otype" :placeholder="$t('table.order_type')" clearable style="width: 150px" class="filter-item" multiple>
                        <el-option v-for="(item, index) in orderTypeOptions" :key="index" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('table.delivery_date')" style="width:40%">
                    <el-date-picker
                        v-model="listQuery.delivery_date"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="-"
                        :start-placeholder="$t('placeholder.delivery_from')"
                        :end-placeholder="$t('placeholder.delivery_to')"
                        value-format="yyyy-MM-dd hh:mm:ss">
                    </el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('table.location')" style="width:25%">
                    <!-- <el-select v-model="listQuery.location_id" :placeholder="$t('table.location')" clearable style="width: 150px" class="filter-item">
                        <el-option v-for="(item, index) in locationOptions" :key="index" :label="item.name" :value="item.id" />
                    </el-select> -->
                    <el-select v-model="listQuery.location_id" name="club_location" :placeholder="$t('table.location')" class="filter-item" style="width: 150px;" multiple>
                        <el-option-group
                        v-for="group in locationOptions"
                        :key="group.id"
                        :label="group.name"
                        :value="group.id">
                        <el-option
                            v-for="item in group.child"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('table.payment_status')" style="width:25%">
                    <el-select v-model="listQuery.is_paid" :placeholder="$t('table.payment_status')" clearable style="width: 150px" class="filter-item" multiple>
                        <el-option v-for="(item, index) in paymentStatusOptions" :key="index" :label="item.name" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="button-box" >
                <el-button v-waves class="filter-item" type="success" icon="el-icon-download"  @click="onDownLoad">{{ $t('table.download') }}</el-button>
                <el-button v-waves class="filter-item" type="success" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
                <el-button v-waves class="filter-item" type="info" icon="el-icon-refresh" @click="syncAxVisible = true">{{ $t('table.sync_ax') }}</el-button>
            </div>
        </div>
        <el-row>
            <el-col :span="24" style="text-align: right;">
                <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="icon iconfont icon-choices" @click="handleCreate">{{ $t('table.add') }}</el-button>
                <el-popover
                placement="bottom"
                width="300"
                v-model="isShow">
                    <div class="email-box">
                        <div class="hd">Select E-mail Type</div>
                        <div>
                            <el-checkbox-group 
                                v-model="multiEtype" :max="1">
                                <el-checkbox label="1">Public/workshop/Event with price</el-checkbox>
                                <el-checkbox label="2">Public/workshop/Event without price</el-checkbox>
                                <el-checkbox label="3">Online with price</el-checkbox>
                                <el-checkbox label="4">Online without price</el-checkbox>
                            </el-checkbox-group>
                            <div class="mail-btn-box">
                                <el-button size="mini" @click="onSendCancel()"  >cancel</el-button>
                                <el-button type="warning" @click="onMultiSend()" size="mini" >Send</el-button>
                            </div>
                        </div>
                    </div>
                    <el-button slot="reference" class="filter-item" type="warning" icon="el-icon-edit" style="margin-top: 10px; margin-left: 10px;">E-mail</el-button>
                </el-popover>
                <el-button class="filter-item" style="margin-top: 10px; "  type="primary" icon="icon iconfont icon-pause-symbol" @click="onMultiOrderHold">Hold</el-button>
                <el-button class="filter-item" style="margin-top: 10px; margin-left: 10px; "  type="success" icon="icon iconfont icon-transfer" @click="onMultiOrderResume">Resume</el-button>
                <el-button class="filter-item" style="margin-top: 10px; "  type="danger" icon="icon iconfont icon-remove-button" @click="onMultiOrderVoid">Void</el-button>
            </el-col>
        </el-row>
        <div class="order-list-box">
            <el-table
            v-loading="listLoading"
            :data="list"
            @selection-change="handleSelectionChange">
                <el-table-column
                type="selection"
                width="55">
                </el-table-column>
                <el-table-column :label="$t('table.ref_no')" align="center" width="110">
                    <template slot-scope="scope">
                        <span>{{ scope.row.sn }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('order_form.order_from')" align="center" width="100">
                    <template slot-scope="scope">
                        <span>{{ scope.row.order_from_name }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.date_in')" align="center" width="100">
                    <template slot-scope="scope">
                        <span>{{ scope.row.order_date_in }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.Customer')" align="center" >
                    <template slot-scope="scope">
                        <span>{{ scope.row.email }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.contact')" align="center" width="120">
                    <template slot-scope="scope">
                        <span>{{ scope.row.mobile }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.status')" align="center" width="65">
                    <template slot-scope="scope">
                        <span>
                            <i class="icon iconfont icon-Unpaid" v-if="scope.row.status === 0 "></i>
                            <i class="el-icon-check f-green" v-if="scope.row.status === 1"></i>
                            <!-- <i class="el-icon-close f-red" v-if="scope.row.status === 0 && scope.row.order_from === 3"></i> -->
                            <i class="icon iconfont icon-transfer" v-if="scope.row.status === 2"></i>
                            <i class="icon iconfont icon-pause-symbol" v-if="scope.row.status === 3"></i>
                            <i class="icon iconfont icon-Success" v-if="scope.row.status === 4"></i>
                            <i class="icon iconfont icon-remove-button" v-if="scope.row.status === 5"></i>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.payment')" align="center" width="80">
                    <template slot-scope="scope">
                        {{ scope.row.payed_at &&  scope.row.payed_at > '1970-01-01' ? 'PAID' : 'UNPAID' }}
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.total_amount')" align="center" width="110">
                    <template slot-scope="scope">
                        {{ scope.row.tprice }}
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.regions')" align="center" width="110">
                    <template slot-scope="scope">
                        {{ scope.row.area_name }}
                    </template>
                </el-table-column>
                <!-- <el-table-column :label="$t('table.remark')" align="center">
                    <template slot-scope="scope">
                        <item-remark :remark="scope.row" ></item-remark>
                    </template>
                </el-table-column> -->
                <el-table-column :label="$t('table.operate')" align="center" width="250">
                    <template slot-scope="scope">
                        <order-cell :item-data="scope.row" :list="list" @to-detail="toDetail" @to-modify="toModify" @on-duplicate="onDuplicate" @get-list="getList"></order-cell>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="90%" :before-close="handleClose" :close-on-click-modal="false">
            
            <el-form ref="dataForm" :rules="rules" :model="orderData" label-position="left" label-width="160px" style="margin-left:30px;">
                <el-row>
                    <el-col :span="24"><div class="ref-form">{{orderData.sn ? $t('table.ref_no')+' : ' + orderData.sn : ''}}</div></el-col>
                    <el-col :span="10">
                        <el-form-item :label="$t('order_form.date_in')">
                            <div v-if="dialogStatus != 'detail'">
                                <el-date-picker
                                    v-model="orderData.order_date_in"
                                    :disabled="dialogStatus == 'modify' || showButton || noEdit"
                                    type="date"
                                    :placeholder="$t('placeholder.date')"
                                    value-format="yyyy-MM-dd hh:mm:ss"
                                    style="width:value-format 300px;">
                                </el-date-picker>
                            </div>
                            <div v-else>
                                {{orderData.order_date_in}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item :label="$t('order_form.contact_number')" required prop="mobile">
                            <div v-if="dialogStatus != 'detail'">
                                <el-input v-model="orderData.mobile" :disabled="showButton || noEdit" name="contact_number" :placeholder="$t('order_form.contact_number')" style="width: 300px;"/>
                            </div>
                            <div v-else>
                                {{orderData.mobile}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="$t('order_form.order_from')">
                            <div v-if="dialogStatus != 'detail'">
                                <el-select v-model="orderData.order_from" :disabled="dialogStatus == 'modify' || showButton || noEdit" class="filter-item" :placeholder="$t('placeholder.select')"  style="width: 300px;">
                                    <el-option v-for="(item, index) in orderFromOptions" :key="index" :label="item.name" :value="item.value" />
                                </el-select>
                            </div>
                            <div v-else>
                                {{orderData.order_from_name}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item :label="$t('order_form.e_mail')" required prop="email">
                            <div v-if="dialogStatus != 'detail'">
                                <el-input v-model="orderData.email" :disabled="showButton || noEdit" name="e_mail" :placeholder="$t('order_form.e_mail')" style="width: 300px;"/>
                            </div>
                            <div v-else>
                                {{orderData.email}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="$t('order_form.club_location')" required prop="club_location">
                            <div v-if="dialogStatus != 'detail'">
                                <!-- <el-select v-model="orderData.club_location" name="club_location" class="filter-item" :placeholder="$t('placeholder.select')"  style="width: 300px;">
                                    <el-option v-for="(item, index) in locationOptions" :key="index" :label="item.name" :value="item.id" />
                                </el-select> -->
                                <el-select v-model="orderData.club_location" :disabled="showButton || noEdit" name="club_location" class="filter-item" :placeholder="$t('placeholder.select')" style="width: 300px;">
                                    <el-option-group
                                    v-for="group in locationOptions2"
                                    :key="group.id"
                                    :label="group.name"
                                    :value="group.id">
                                    <el-option
                                        v-for="item in group.child"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                    </el-option-group>
                                </el-select>
                            </div>
                            <div v-else>
                                {{orderData.club_location}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item :label="$t('order_form.remark')">
                            <div v-if="dialogStatus != 'detail'">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    :disabled="showButton || noEdit"
                                    :placeholder="$t('placeholder.input')"
                                    v-model="orderData.remark"
                                    style=" width: 300px;">
                                </el-input>
                            </div>
                            <div v-else>
                                {{orderData.remark}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="$t('order_form.card_holder_number')">
                            <el-row :gutter="10" v-if="dialogStatus != 'detail'">
                                <el-col :span="8"><el-input v-model="orderData.cardholder_number" :disabled="showButton || noEdit" :placeholder="$t('order_form.card_holder_number')" name="card_holder_number" icon="el-icon-location"/></el-col>
                                <el-col :span="4"><el-button v-waves class="filter-item" type="primary" :disabled="showButton || noEdit" @click="handleCardNumber">{{ $t('order_form.live_check') }}</el-button></el-col>
                            </el-row>
                            <div v-else>
                                {{orderData.cardholder_number}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item :label="$t('order_form.leaflet_language')">
                            <div v-if="dialogStatus != 'detail'">
                                <el-radio v-model="orderData.leaflet_language" :disabled="showButton || noEdit" :label="1">{{ $t('order_element.language.eng') }}</el-radio>
                                <el-radio v-model="orderData.leaflet_language" :disabled="showButton || noEdit" :label="2">{{ $t('order_element.language.cn') }}</el-radio>
                            </div>
                            <div v-else>
                                {{orderData.leaflet_language === 1 ? $t('order_element.language.eng') : $t('order_element.language.cn')}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="$t('order_form.mbo_location')">
                            <div v-if="dialogStatus != 'detail'">
                                <el-select v-model="orderData.mbo_location" :disabled="showButton || noEdit" name="mbo_location" class="filter-item" :placeholder="$t('placeholder.select')"  style="width: 300px;">
                                    <el-option v-for="(item, index) in areaOptions" :key="index" :label="item.name" :value="item.id" />
                                </el-select>
                            </div>
                            <div v-else>
                                {{orderData.mbo_location}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item :label="$t('order_form.allergies')">
                            <div v-if="dialogStatus != 'detail'">
                                <el-radio v-model="orderData.allergie" :disabled="showButton || noEdit" :label="1">{{ $t('order_element.choose.yes') }}</el-radio>
                                <el-radio v-model="orderData.allergie" :disabled="showButton || noEdit" :label="0">{{ $t('order_element.choose.no') }}</el-radio>
                                <div>If yes, please state them below and refer to the menu well as the <br/>
                                medical considerations</div>
                                <el-input  type="textarea"
                                        :rows="2"
                                        :disabled="showButton || noEdit"
                                        :placeholder="$t('placeholder.input')"
                                        v-model="orderData.allergie_text" name="allergie_text" style="width: 300px;"/>
                            </div>
                            <div v-else>
                                {{orderData.allergie === 1 ? $t('order_element.choose.yes') : $t('order_element.choose.no')}}<br/>
                                {{orderData.allergie_text}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="$t('order_form.name')" required>
                            <div v-if="dialogStatus != 'detail'">
                                <el-form-item prop="fristname" style="display: inline-block">
                                    <el-input v-model="orderData.fristname" :disabled="showButton || noEdit" :placeholder="$t('placeholder.first_name')" name="fristname" style="width: 150px;" />
                                </el-form-item>
                                <el-form-item prop="lastname" style="display: inline-block">
                                    <el-input v-model="orderData.lastname" :disabled="showButton || noEdit" :placeholder="$t('placeholder.last_name')" name="lastname" style="width: 150px;"  />
                                </el-form-item>
                            </div>
                            <div v-else>
                                {{orderData.fristname}}{{orderData.lastname}}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item :label="$t('order_form.juice_cleanse_before')">
                            <div v-if="dialogStatus != 'detail'">
                                <el-radio v-model="orderData.juice_cleanse_before" :disabled="showButton || noEdit" :label="1">{{ $t('order_element.choose.yes') }}</el-radio>
                                <el-radio v-model="orderData.juice_cleanse_before" :disabled="showButton || noEdit" :label="0">{{ $t('order_element.choose.no') }}</el-radio>
                                <div>If yes, What type and level</div>
                                <el-input  type="textarea"
                                        :rows="2"
                                        :disabled="showButton || noEdit"
                                        :placeholder="$t('placeholder.input')"
                                        v-model="orderData.juice_cleanse_before_text" name="juice_cleanse_before_text" style="width: 300px;"/>
                            </div>
                            <div v-else>
                                {{orderData.juice_cleanse_before === 1 ? $t('order_element.choose.yes') : $t('order_element.choose.no')}}<br/>
                                {{orderData.juice_cleanse_before_text}}
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div v-if="dialogStatus === 'detail' || showButton || noEdit || (dialogStatus !== 'create' && orderData.payed_at && orderData.payed_at > '1970-01-01')">
                    <!-- <el-row class="orders-row" style="margin-bottom:0">
                        <el-col :span="8">
                            <div class="grid-content bg-grey-light center">Package</div>
                        </el-col>
                        <el-col :span="6">
                            <div class="grid-content bg-grey-light center">Localtion</div>
                        </el-col>
                        <el-col :span="3"><div class="grid-content bg-grey-light center">Delivery Date</div></el-col>
                        <el-col :span="3"><div class="grid-content bg-grey-light center">AX Status</div></el-col>
                        <el-col :span="4"><div class="grid-content bg-grey-light center">Collected Date Confirm</div></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24" v-for="(group, t) in orderData.group" :key="t" style="margin-bottom:0" class="order-group-products">
                            <order-product :item="orderData" :group="group" :idx="t" :location-options="locationOptions"></order-product>
                        </el-col>
                    </el-row> -->
                    <order-infos v-for="(assemble, index) in assembles" :home-list="homeList" :show-button="showButton || noEdit" :order-data="assemble" :key="index" :location-options="locationOptions" :product-options="productOptions"  @change-data="changeAssemble"></order-infos>
                </div>
                <div class="order-product-container" v-else>
                    <!-- <div class="order-product-hd">
                        <el-row>
                            <el-col :span="6"><span class="y-label">{{$t('table.package')}}</span>
                                <el-select v-model="orderData.package" class="filter-days" :placeholder="$t('placeholder.select')" value-key="id" style="width: 100px;" size="mini" @change="changePackage">
                                    <el-option v-for="(item, index) in groupList" :key="index" :label="item.name" :value="item" />
                                </el-select>
                            </el-col>
                            <el-col :span="6"><span class="y-label">No. of Days</span>
                                <el-select v-model="orderData.day" class="filter-days" :placeholder="$t('placeholder.select')"  style="width: 60px;" size="mini" @change="changeDay">
                                    <el-option v-for="(item, index) in days" :key="index" :label="item" :value="item" />
                                </el-select>
                            </el-col>
                            <el-col :span="6"><span class="y-label">Date</span>
                                <el-date-picker
                                    v-model="orderData.scheduled_at"
                                    type="date"
                                    placeholder="选择日期" size="mini" style=" width: 150px;">
                                </el-date-picker></el-col>
                            <el-col :span="6"><span class="y-label">Total</span> <el-input v-model="orderData.total" name="filterTotal"  style="width: 100px;" size="mini" /></el-col>
                        </el-row>
                    </div>
                    <div class="order-product-main" v-for="(group, index) in orderData.group" :key= "index">
                        <group-product :day="index" :locations="locationOptions" :start-date="orderData.scheduled_at" :group-options = "groupList" :order-data="group" :products="products"></group-product>
                    </div> -->
                    <order-info-list v-for="(assemble, index) in assembles" :orders="orderData" :order-datas="assemble" :key="index" :idx="index" :custom-group-id="custom_group_id" :group-list="groupList" :location-options="locationOptions" :home-list="homeList" :products="products" :product-options="productOptions" :days="days" @change-data="changeAssemble"></order-info-list>
                    <el-row style="text-align: right">
                        <el-button type="primary" @click="addAssemble()" class="el-icon-plus" size="mini" > Add</el-button>
                        <el-button type="primary" v-if="assembles.length > 1" @click="delAssemble()" class="el-icon-minus" size="mini" > Del</el-button>
                    </el-row>
                </div>
                <div>
                    <el-row class="total-text" style="padding: 10px 5px;background-color: #eee;margin-top: 10px;    font-weight: 700;">
                        <el-col style="text-align: right" :span="21">Total Items:</el-col>
                        <el-col class="total-underline" :span="3"> {{assembles.length}}</el-col>
                        <el-col style="text-align: right" :span="21">Delivery Change:</el-col>
                        <el-col class="total-underline" :span="3"> ${{orderData.delivery}}</el-col>
                        <el-col style="text-align: right" :span="21">Total Amount:</el-col>
                        <el-col class="total-underline" :span="3"> ${{orderData.tprice}}</el-col>
                    </el-row>
                </div>
                <div class="order-footer-box">
                    <el-row style="line-height:22px;">
                        <el-col :span="11">
                            <div>Remark</div>
                            <div  v-if="dialogStatus != 'detail'">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    :disabled="showButton || noEdit"
                                    :placeholder="$t('placeholder.input')"
                                    v-model="orderData.payment_remark"
                                    style=" width: 380px;">
                                </el-input>
                            </div>
                            <div v-else>
                                <item-remark :item-data="orderData" ></item-remark>
                            </div>
                        </el-col>
                        <el-col :span="12" :offset="1">
                            <el-row :gutter="10">
                                <el-col :span="6"><div class="grid-content bg-purple">{{ $t('order_form.method') }}</div></el-col>
                                <el-col :span="6"><div class="grid-content bg-purple">{{ $t('order_form.ref') }}</div></el-col>
                                <el-col :span="6"><div class="grid-content bg-purple">{{ $t('order_form.amount') }}</div></el-col>
                            </el-row>
                            <el-row :gutter="10" v-for="(item, index) in orderData.payment" :key="index" style="margin-top:10px;">
                                <el-col :span="6" >
                                    <div class="grid-content bg-purple" v-if="dialogStatus != 'detail'">
                                        <el-select v-model="item.payment_method" :disabled="!!orderData.payed_at || showButton || noEdit" :placeholder="$t('placeholder.select')" clearable style="width:150px" class="filter-item">
                                            <el-option v-for="(it, index) in paymentOptions" :key="index" :label="it.name" :value="it.id" />
                                        </el-select>
                                    </div>
                                    <div v-else>
                                        {{item.payment_method}}
                                    </div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="grid-content bg-purple" v-if="dialogStatus != 'detail'">
                                        <el-input v-model="item.ref" name="ref[]" :disabled="!!orderData.payed_at || showButton || noEdit" />
                                    </div>
                                    <div v-else>
                                        {{item.ref}}
                                    </div>
                                </el-col>
                                <el-col :span="6">
                                    <div class="grid-content bg-purple" v-if="dialogStatus != 'detail'">
                                        <el-input type="number" v-model.number="item.amount" :disabled="!!orderData.payed_at || showButton || noEdit" name="amount[]" @change="changePayment" />
                                    </div>
                                    <div v-else>
                                        {{item.amount}}
                                    </div>
                                </el-col>
                            </el-row>
                            <el-row v-if="dialogStatus != 'detail'" >
                                <el-button style="font-size:20px;" type="text" @click="addPayment()" :disabled="!!orderData.payed_at || showButton || noEdit" class="el-icon-circle-plus-outline" ></el-button>
                                <el-button style="font-size:20px;" type="text" @click="delPayment()" :disabled="!!orderData.payed_at || showButton || noEdit" class="el-icon-remove-outline" ></el-button>
                            </el-row>
                        </el-col>
                    </el-row>
                    <el-row class="total-text" >
                        <el-col style="text-align: right" :span="21">Balance:</el-col>
                        <el-col class="total-underline" :span="3">$ {{orderData.balance}}</el-col>
                    </el-row>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <div v-if="!showButton">
                    <el-button @click="handleClose"  v-if="dialogStatus != 'detail'">{{ $t('table.cancel') }}</el-button>
                    <el-button type="primary" @click="confirmData()"  v-if="dialogStatus != 'detail' && orderData.status !== 5">{{ $t('table.confirm') }}</el-button>
                </div>
                <div v-if="showButton">
                    <el-button @click="showButton = false" style="float:left" >Prev Step</el-button>
                    <el-button type="primary" @click="createData(1)"  v-if="dialogStatus != 'detail'">Confirm & E-mail</el-button>
                    <el-button @click="createData(0)" class="filter-item" type="success" style="margin-left: 10px;">Only Confirm</el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="Sync Ax" :visible.sync="syncAxVisible" >
            <el-form :model="syncForm">
                <el-row>
                    <el-col :span="18" >
                        <el-form-item style="width:40%">
                            <el-date-picker
                                v-model="syncForm.delivery_date"
                                type="daterange"
                                align="right"
                                unlink-panels
                                range-separator="-"
                                :start-placeholder="$t('placeholder.date_from')"
                                :end-placeholder="$t('placeholder.date_to')"
                                value-format="yyyy-MM-dd hh:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" >
                        <el-form-item>
                            <el-button type="info" @click="searchSyncAx" >Search</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-table :data="order_items" width="100%">
                <el-table-column :label="$t('table.order_no')" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.order_no }}
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.no_of_days')" align="center" >
                    <template slot-scope="scope">
                        {{ scope.row.no_of_day }}
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.delivery_date')" align="center" >
                    <template slot-scope="scope">
                        {{ scope.row.delivery_date }}
                    </template>
                </el-table-column>
                <el-table-column :label="$t('table.delivery_day')" align="center" >
                    <template slot-scope="scope">
                        {{ scope.row.delivery_day }}
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="syncAxVisible = false">Cancel</el-button>
                <el-button type="primary" @click="sendSyncAx">Send</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { fetchStore, fetchList, fetchHold, fetchResume, fetchOrderVoid, fetchUpdateOrder, fetchPaytype, fetchOrderEmail, fetchShow, fetchSyncAx, fetchPostSyncAx } from '@/api/order'
import { fetchAll } from '@/api/location'
import { fetchAll as fetchGroupList } from '@/api/group'
import { fetchAll as fetchProductList } from '@/api/product'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import GroupProduct from '@/components/GroupProduct'
import OrderProduct from '@/components/GroupProduct/OrderProduct'
import ItemRemark from '@/components/OrderItem/ItemRemark'
import OrderCell from '@/components/OrderItem/OrderCell'
import OrderInfoList from '@/components/OrderItem/OrderInfoList'
import OrderInfos from '@/components/OrderItem/OrderInfos'
/* import OrderItem from '@/components/OrderItem' */
import i18n from '@/lang/index'
import { groupBy, formatData, urlEncode, setLocationType, calcTime } from '@/utils'
import { mapGetters } from 'vuex'

export default {
    name: 'Order',
    components: { Pagination, GroupProduct, OrderProduct, ItemRemark, OrderCell, OrderInfoList, OrderInfos },
    directives: { waves },
    data () {
        return {
            custom_group_id: 22,
            tableKey: 0,
            lang: i18n.locale,
            total: 0,
            list: [],
            listLoading: true,
            listQuery: {
                keyword: '',
                /* start_date_in: formatData(new Date()),
                end_date_in: formatData(new Date()), */
                group_id: '',
                product_id: [],
                /* start_delivery_date: formatData(new Date()),
                end_delivery_date: formatData(new Date()), */
                // group_id: '',
                // product_id: '',
                // location_id: '',
                // is_paid: 2,
                // otype: 0,
                location_id: [],
                is_paid: [],
                otype: [],
                page: 1,
                limit: 20,
                // status: 99,
                status: [],
                lang: i18n.locale,
                user_id: 0
            },
            statusOptions: [
                // {
                //     name: i18n.t('order_element.status.all'),
                //     value: 99
                // },
                {
                    name: 'UNPAID',
                    value: 0
                },
                {
                    name: 'PAID',
                    value: 1
                },
                {
                    name: 'RESUME',
                    value: 2
                },
                {
                    name: 'HOLD',
                    value: 3
                },
                {
                    name: 'SUCCESS',
                    value: 4
                },
                {
                    name: 'VOID',
                    value: 5
                }
            ],
            packageOptions: [
                {
                    name: i18n.t('order_element.package.all'),
                    value: 0
                }
            ],
            orderTypeOptions: [
                // {
                //     name: 'All',
                //     value: 0
                // },
                {
                    name: 'Delivery',
                    value: 1
                },
                {
                    name: 'Instant',
                    value: 2
                }
            ],
            orderFromOptions: [
                {
                    name: 'Public',
                    value: 0
                },
                {
                    name: 'Workshop',
                    value: 1
                },
                {
                    name: 'Event',
                    value: 2
                },
                {
                    name: 'Online',
                    value: 3
                }
            ],
            langOptions: [
                {
                    name: i18n.t('order_element.language.eng'),
                    value: 0
                },
                {
                    name: i18n.t('order_element.language.cn'),
                    value: 1
                }
            ],
            paymentOptions: [
                {
                    name: i18n.t('order_element.payment.paypal'),
                    id: 0
                },
                {
                    name: i18n.t('order_element.payment.weixin'),
                    id: 1
                },
                {
                    name: i18n.t('order_element.payment.zhifubao'),
                    id: 2
                }
            ],
            paymentStatusOptions: [
                // {
                //     name: 'All',
                //     value: 2
                // },
                {
                    name: 'UNPAID',
                    value: 0
                },
                {
                    name: 'PAID',
                    value: 1
                }
            ],
            dialogFormVisible: false,
            dialogStatus: 'create',
            textMap: {
                update: 'Edit',
                create: 'Create',
                detail: 'Detail'
            },
            orderData: {
                id: undefined,
                order_date_in: new Date(),
                order_from: 0,
                order_from_name: '',
                fristname: '',
                lastname: '',
                cardholder_number: '',
                club_location: 0,
                mbo_location: 96,
                mobile: '',
                email: '',
                remark: '',
                scheduled_at: new Date(),
                leaflet_language: 1,
                allergie: 0,
                allergie_text: '',
                juice_cleanse_before: 0,
                juice_cleanse_before_text: '',
                day: 1,
                delivery: 0,
                tprice: 0,
                payment: [
                    {
                        payment_method: 0,
                        ref: 0,
                        amount: 0
                    }
                ],
                assemble: [{
                    group_id: 22,
                    group_name: 'Custom Cleanse',
                    day: 1,
                    scheduled_at: new Date(),
                    group:[{
                        group_id: 22,
                        name: 'Custom Cleanse',
                        location_id: '',
                        area_region_id: '',
                        scheduled_at: new Date(),
                        product:[
                            {id: '', qty: 1, product_name: '', product_mphoto: ''},
                            {id: '', qty: 1, product_name: '', product_mphoto: ''},
                            {id: '', qty: 1, product_name: '', product_mphoto: ''},
                            {id: '', qty: 1, product_name: '', product_mphoto: ''},
                            {id: '', qty: 1, product_name: '', product_mphoto: ''},
                            {id: '', qty: 1, product_name: '', product_mphoto: ''},
                            {id: '', qty: 1, product_name: '', product_mphoto: ''},
                            {id: '', qty: 1, product_name: '', product_mphoto: ''}
                        ],
                        home_locations: [],
                        delivery: 0
                    }]
                }],
                etype: []
            },
            rules: {
                fristname: [{ required: true, message: 'fristName is required', trigger: 'blur' }],
                lastname: [{ required: true, message: 'lastName is required', trigger: 'blur' }],
                mobile: [{ required: true, message: 'contact number is required', trigger: 'blur' }],
                email: [{ required: true, message: 'email is required', trigger: 'blur' }],
                club_location: [{ required: true, message: 'club location is required', trigger: 'blur' }]
            },
            days: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            locationOptions: [],
            locationOptions2: [],
            groupList: [],
            products: [],
            prices: [],
            productOptions: [],
            isEditPayRemark: false,
            isEditRemark: false,
            isShow: false,
            multSelected: [],
            homeList: [],
            multiEtype: [],
            assembles: [{
                group_id: 22,
                group_name: 'Custom Cleanse',
                day: 1,
                scheduled_at: new Date(),
                group:[{
                    group_id: 22,
                    name: 'Custom Cleanse',
                    location_id: '',
                    area_region_id: '',
                    scheduled_at: new Date(),
                    product:[
                        {id: '', qty: 1, product_name: '', product_mphoto: ''},
                        {id: '', qty: 1, product_name: '', product_mphoto: ''},
                        {id: '', qty: 1, product_name: '', product_mphoto: ''},
                        {id: '', qty: 1, product_name: '', product_mphoto: ''},
                        {id: '', qty: 1, product_name: '', product_mphoto: ''},
                        {id: '', qty: 1, product_name: '', product_mphoto: ''},
                        {id: '', qty: 1, product_name: '', product_mphoto: ''},
                        {id: '', qty: 1, product_name: '', product_mphoto: ''}
                    ],
                    home_locations: [],
                    delivery: 0
                }]
            }],
            syncAxVisible: false,
            syncForm: {
                ax_sync_item_status: 0,
                delivery_start_date: new Date(),
                delivery_end_date: new Date()
            },
            order_ids: [],
            order_items: [],
            ax_delivery_start_date: '',
            ax_delivery_end_date: '',
            showButton: false,
            noEdit: false,
            customProducts: [
                {id: '', qty: 0, product_name: '', product_mphoto: ''},
                {id: '', qty: 0, product_name: '', product_mphoto: ''},
                {id: '', qty: 0, product_name: '', product_mphoto: ''},
                {id: '', qty: 0, product_name: '', product_mphoto: ''},
                {id: '', qty: 0, product_name: '', product_mphoto: ''},
                {id: '', qty: 0, product_name: '', product_mphoto: ''},
                {id: '', qty: 0, product_name: '', product_mphoto: ''},
                {id: '', qty: 0, product_name: '', product_mphoto: ''}
            ]
        }
    },
    created() {
        this.getList()
        this.getLocation()
        this.getGroupList()
        this.getProduct()
        this.orderData.mbo_location = 96
        // console.log('process.env', process.env.BASE_API)
        this.getuserid()
        this.getPaytype()
    },
    mounted () {
        console.log(this.changeStatus)
        if (this.changeStatus) {
            this.handleCreate()
            this.orderData.userId = this.userData.id
            this.orderData.name = this.userData.name
            this.orderData.fristname = this.userData.first_name
            this.orderData.lastname = this.userData.last_name
            this.orderData.email = this.userData.email
            this.orderData.mobile = this.userData.mobile
            this.$store.dispatch('setStatus', 0)
        }
    },
    computed: {
        areaOptions: function () {
            return this.$store.state.locale.areas
        },
        ...mapGetters([
            'userData',
            'changeStatus'
        ])
    },
    methods: {
        getPaytype() { // 获取支付方式
            var _this = this
            fetchPaytype().then(res => {
                var data = res.data
                _this.paymentOptions = data.data
            })
        },
        getProduct() {
            var _this = this
            this.listLoading = true
            var params = {
                /* lang: i18n.locale,
                area: 96, */
                category_name: ['JUICES', 'SUPPLEMENT']
            }
            fetchProductList(params).then(response => {
                var data = response.data
                _this.productOptions = data.data
                // Just to simulate the time of the request
                setTimeout(() => {
                    _this.listLoading = false
                }, 1.5 * 1000)
            })
        },
        getList() { // 获取订单列表
            this.listLoading = true
            if (this.listQuery.date_in) {
                this.listQuery.start_date_in = formatData(this.listQuery.date_in[0]).substr(0, 10)
                this.listQuery.end_date_in = formatData(this.listQuery.date_in[1]).substr(0, 10)
            } else {
                delete this.listQuery.start_date_in
                delete this.listQuery.end_date_in
            }
            if (this.listQuery.delivery_date) {
                this.listQuery.start_delivery_date = formatData(this.listQuery.delivery_date[0]).substr(0, 10)
                this.listQuery.end_delivery_date = formatData(this.listQuery.delivery_date[1]).substr(0, 10)
            } else {
                delete this.listQuery.start_delivery_date
                delete this.listQuery.end_delivery_date
            }
            fetchList(this.listQuery).then(response => {
                var data = response.data
                this.list = data.data.data
                this.total = data.data.total
                // Just to simulate the time of the request
                setTimeout(() => {
                    this.listLoading = false
                }, 1.5 * 1000)
            }).catch(err => {
                console.log(err)
                this.listLoading = false
            })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        resetTemp() {
            this.orderData = {
                id: undefined,
                order_date_in: new Date(),
                order_from: 0,
                order_from_name: '',
                fristname: '',
                lastname: '',
                cardholder_number: '',
                club_location: 0,
                mbo_location: 96,
                mobile: '',
                email: '',
                remark: '',
                scheduled_at: new Date(),
                leaflet_language: 1,
                allergie: 0,
                allergie_text: '',
                juice_cleanse_before: 0,
                juice_cleanse_before_text: '',
                day: 1,
                delivery: 0,
                tprice: 0,
                payment: [
                    {
                        payment_method: 0,
                        ref: 0,
                        amount: 0
                    }
                ],
                assemble: [{
                    group_id: this.custom_group_id,
                    day: 1,
                    scheduled_at: new Date(),
                    group:[{
                        group_id: this.custom_group_id,
                        location_id: '',
                        area_region_id: '',
                        scheduled_at: new Date(),
                        product: this.customProducts,
                        home_locations: [],
                        delivery: 0
                    }]
                }],
                etype: [],
                balance: 0
            }
            this.assembles = [{
                group_id: this.custom_group_id,
                day: 1,
                scheduled_at: new Date(),
                group:[{
                    group_id: this.custom_group_id,
                    location_id: '',
                    area_region_id: '',
                    scheduled_at: new Date(),
                    product: this.customProducts,
                    home_locations: [],
                    delivery: 0
                }]
            }]
        },
        handleCreate() {
            this.resetTemp()
            this.showButton = false
            this.noEdit = false
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        /* changePackage() {
            this.orderData.group.push(this.orderData.package)
            this.products = this.orderData.package.product
            this.prices = this.orderData.package.price
        },
        changeDay() { // 修改天数
            let len = this.orderData.group.length, day = this.orderData.day
            if (day < len) {
                this.orderData.group.splice(day, len - day)
            } else {
                for (let i = 0; i < day; i++) {
                    if (i >= len) {
                        this.orderData.group.push(this.orderData.package)
                    }
                }
            }
            this.getTotal()
        }, */
        getLocation() {// 地址列表
            const _this = this
            let params = {
                /* area: this.$store.getters.area */
                pid: 0
            }
            fetchAll(params).then((res) => {
                let datas = res.data.data
                _this.locationOptions = setLocationType(datas)
                _this.locationOptions2 = JSON.parse(JSON.stringify(setLocationType(datas)))
                _this.locationOptions2.push({pid: 0, name: "other", id: 9999, child: [{pid: 0, name: "kitchen", id: 0}]})
                let homeId = []
                datas.forEach(home => {
                    if(home.type === 0){
                        homeId.push(home.id)
                    }
                })
                this.homeList = homeId
                // this.locationOptions = res.data.data
            })
        },
        getGroupList() {
            const _this = this
            let params = {
                lang: i18n.locale,
                /* area: 96,
                name: '' */
            }
            let flag = 0
            fetchGroupList(params).then((res) => {
                let datas = JSON.parse(JSON.stringify(res.data.data))
                if (datas.length > 0) {
                    datas.forEach(element => {
                        if (element.is_custom === 1) {
                            if (flag === 0) {
                                _this.custom_group_id = element.id
                                flag = 1
                            }
                            /* element.product = [
                                {id: '', qty: 1, product_name: '', product_mphoto: ''},
                                {id: '', qty: 1, product_name: '', product_mphoto: ''},
                                {id: '', qty: 1, product_name: '', product_mphoto: ''},
                                {id: '', qty: 1, product_name: '', product_mphoto: ''},
                                {id: '', qty: 1, product_name: '', product_mphoto: ''},
                                {id: '', qty: 1, product_name: '', product_mphoto: ''},
                                {id: '', qty: 1, product_name: '', product_mphoto: ''},
                                {id: '', qty: 1, product_name: '', product_mphoto: ''}
                            ] */
                            element.product.forEach(ele => {
                                ele.qty = 0
                                return ele
                            })
                            console.log(element.product)
                            _this.customProducts = JSON.parse(JSON.stringify(element.product))
                        }
                        element.location_id = ''
                        element.area_region_id = ''
                        element.home_locations = []
                        element.scheduled_at = new Date()
                        return element
                    })
                    _this.groupList = datas
                    _this.orderData.package = datas[0]
                    _this.products = datas[0].product
                    _this.prices = datas[0].price
                    // _this.changePackage()
                }
            })
        },
        checkEmpty(){
            let isEmpty = false
            this.cartObj.group.forEach(item => {
                item.product.forEach(pd => {
                    if(!pd.product_id){
                        isEmpty = true
                    }
                });
            })
            return isEmpty
        },
        confirmData() {// 添加订单
            let _this = this
            let isTrue = true
            if(this.assembles.length > 0) {
                this.assembles.forEach(ele => {
                    if(!ele.scheduled_at) {
                        _this.$alert('<strong class="orange">Please Select Delivery Date</strong>', 'Message', {
                            dangerouslyUseHTMLString: true
                        })
                        isTrue = false
                        return
                    }
                    ele.group.forEach(element => {
                        if(!element.scheduled_at) {
                            _this.$alert('<strong class="orange">Please Select Delivery Date</strong>', 'Message', {
                                dangerouslyUseHTMLString: true
                            })
                            isTrue = false
                            return
                        }
                        let isEmpty = false
                        let juiceNum = 0
                        let supNum = 0

                        element.product.forEach(pd => {
                            if(!pd.product_id){
                                isEmpty = true
                            }
                            if (pd.qty > 0) {
                                if (pd.product_id === 17 || pd.product_id === 18) {
                                    ++supNum
                                } else if(pd.product_id !== 17 || pd.product_id !== 18){
                                   juiceNum = juiceNum + pd.qty
                                }
                            }
                            
                        })

                        if (element.group_id === _this.custom_group_id){
                            if (supNum !== 2) {
                                _this.$alert('<strong class="orange">Only two supplement are available</strong>', 'Message', {
                                    dangerouslyUseHTMLString: true
                                })
                                isTrue = false
                                return
                            }
                            if (juiceNum < 8) {
                                _this.$alert('<strong class="orange">Eight bottles of juice need to be filled</strong>', 'Message', {
                                    dangerouslyUseHTMLString: true
                                })
                                isTrue = false
                                return
                            }
                            if (juiceNum > 8) {
                                _this.$alert('<strong class="orange">Only eight bottles of juice are available</strong>', 'Message', {
                                    dangerouslyUseHTMLString: true
                                })
                                isTrue = false
                                return
                            }
                        }
                        if(isEmpty){
                            _this.$alert('<strong class="orange">Please pick a juice for empty bottle</strong>', 'Message', {
                                dangerouslyUseHTMLString: true
                            })
                            isTrue = false
                            return
                        }
                        if(element.location_id) {
                            if (_this.homeList.indexOf(element.location_id) > -1) {
                                if (!element.area_region_id) {
                                    _this.$alert('<strong class="orange">Please Select District</strong>', 'Message', {
                                        dangerouslyUseHTMLString: true
                                    })
                                    isTrue = false
                                    return
                                } else {
                                    if (!element.address) {
                                        _this.$alert('<strong class="orange">Please fill out the address</strong>', 'Message', {
                                            dangerouslyUseHTMLString: true
                                        })
                                        isTrue = false
                                        return
                                    }
                                }
                            }
                        } else {
                            _this.$alert('<strong class="orange">Please Select Location</strong>', 'Message', {
                                dangerouslyUseHTMLString: true
                            })
                            isTrue = false
                            return
                        }
                    })
                })
            }
            if(this.orderData.payment.length > 0) {
                this.orderData.payment.forEach(ele => {
                    if (!ele.payment_method) {
                        _this.$alert('<strong class="orange">Please Select Payment Method</strong>', 'Message', {
                            dangerouslyUseHTMLString: true
                        })
                        isTrue = false
                    }
                    if (!ele.amount) {
                        _this.$alert('<strong class="orange">Please Input Amount</strong>', 'Message', {
                            dangerouslyUseHTMLString: true
                        })
                        isTrue = false
                    }
                })
            }
            if (_this.orderData.balance < 0) {
                _this.$alert('<strong class="orange">Balance should not be less than 0</strong>', 'Message', {
                    dangerouslyUseHTMLString: true
                })
                isTrue = false
            }
            if (!isTrue) return
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
                    // this.temp.author = 'vue-element-admin'
                   _this.showButton = true
                }
            })
        },
        createData(tag) {
            console.log(tag)
            let _this = this
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    _this.orderData.assemble = JSON.parse(JSON.stringify(_this.assembles))
                    _this.orderData.assemble.forEach(element => {
                        element.scheduled_at = formatData(element.scheduled_at)
                        delete element.package
                        element.group.forEach(ele => {
                            delete ele.home_locations
                            return ele
                        })
                        return element
                    })
                    
                    _this.orderData.lang = i18n.locale
                    if (this.dialogStatus === 'modify') {
                        fetchUpdateOrder(_this.orderData.id, _this.orderData).then((res) => {
                            _this.list.unshift(_this.orderData)
                            _this.dialogFormVisible = false
                            if (tag === 1) {
                                _this.multSelected = res.data.data.id
                                _this.multiEtype = _this.orderData.order_from === 3 ? [3] : [1]
                                _this.sendMail()
                            } else {
                                _this.showButton = false
                                _this.$notify({
                                    title: 'Message',
                                    message: 'Success！',
                                    type: 'success',
                                    duration: 2000
                                })
                            }
                            _this.getList()
                        })
                    } else {
                        fetchStore(_this.orderData).then((res) => {
                            _this.list.unshift(_this.orderData)
                            _this.dialogFormVisible = false
                            if (tag === 1) {
                                _this.multSelected = res.data.data.id
                                _this.multiEtype = _this.orderData.order_from === 3 ? [3] : [1]
                                _this.sendMail()
                            } else {
                                _this.showButton = false
                                _this.$notify({
                                    title: 'Message',
                                    message: 'Success！',
                                    type: 'success',
                                    duration: 2000
                                })
                            }
                            _this.getList()
                        })
                    } 
                }
            })
        },
        sendMail() {
            let _this = this
            let params = {
                order_id: this.multSelected,
                etype: this.multiEtype.join()
            }
            fetchOrderEmail(this.multSelected, params).then(() => {
                _this.multiEtype = []
                _this.showButton = false
                _this.$notify({
                    title: 'Message',
                    message: 'Success！',
                    type: 'success',
                    duration: 2000
                })
            })
        },
        addAssemble() {
            let item = {
                group_id: this.custom_group_id,
                day: 1,
                scheduled_at: new Date(),
                group:[{
                    group_id: this.custom_group_id,
                    location_id: '',
                    area_region_id: '',
                    scheduled_at: new Date(),
                    product: this.customProducts,
                    home_locations: [],
                    delivery: 0
                }]
            }
            this.assembles.push(item)
        },
        delAssemble() {
            let len = this.assembles.length
            if (len > 1) {
                this.assembles.splice(len-1, 1)
            }
        },
        getTotal() {
            let _this = this
            let assemble = this.assembles
            let total = 0, freight = 0
            assemble.forEach(ele => {
                total += parseFloat(ele.total)
                let groups = ele.group
                for (let j = 0; j < groups.length; j++) {
                    if (groups[j].freight) {
                        freight += parseFloat(groups[j].freight)
                    }
                }
            })
            this.orderData.total = total
            this.orderData.delivery = freight
            this.orderData.tprice = parseFloat(total + freight)
        },
        addPayment() {
            let item = {
                payment_method: '',
                ref: '',
                amount: 0
            }
            this.orderData.payment.push(item)
        },
        delPayment() { // @TODO
            let len = this.orderData.payment.length
            if (len > 1) {
                this.orderData.payment.splice(len-1, 1)
            }
        },
        changePayment() {
            this.getBalance(this.orderData.payment)
        },
        handleCardNumber() {
            console.log(555)
        },
        onDownLoad() { //跳转下载页
            let query = urlEncode(this.listQuery)
            let url = process.env.BASE_API + '/admin/order-delivery-export?1=1' + query
            window.open(url)
        },
        onDuplicate(item) {// 暂停订单
            this.showButton = false
            this.noEdit = false
            this.orderData = JSON.parse(JSON.stringify(item))
            this.orderData.assemble.forEach(element => {
                element.group.forEach(ele => {
                    ele.freight = ele.delivery
                    return ele
                })
            })
            this.orderData.order_date_in = new Date()
            this.orderData.sn = ''
            this.orderData.status = 0
            this.orderData.payed_at = ''
            this.assembles = this.orderData.assemble
            this.orderData.order_from = 0
            this.orderData.payed_model = 0
            this.getTotal()
            this.getBalance(this.orderData.payment)
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
        },
        toDetail(item) {
            this.orderData = JSON.parse(JSON.stringify(item))
            this.dialogStatus = 'detail'
            this.dialogFormVisible = true
        },
        toModify(item) { // 获取详情
            /* const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            }) */
            let _this = this
            fetchShow(item.id).then((res) => {
                _this.orderData = JSON.parse(JSON.stringify(res.data.data))
                console.log(_this.orderData.status)
                if (_this.orderData.status === 5) {
                    _this.noEdit = true
                } else {
                    _this.noEdit = false
                }
                _this.orderData.assemble.forEach(element => {
                    element.group.forEach(ele => {
                        ele.freight = ele.delivery
                        return ele
                    })
                })
                _this.assembles = _this.orderData.assemble
                _this.getTotal()
                _this.getBalance(_this.orderData.payment)
                _this.dialogStatus = 'modify'
                _this.dialogFormVisible = true
            }).catch(err => {
            })
        },
        getBalance(payment) {
            let amount = 0
            if(payment.length > 0) {
                payment.forEach(ele => {
                    if (!ele.amount) {
                        ele.amount = 0
                    }
                    amount += parseFloat(ele.amount)
                })
            }
            this.orderData.balance = this.orderData.tprice - amount
        },
        getuserid(){
            if (this.listQuery.user_id != 'undefined'){
                this.listQuery.user_id = this.$route.query.user_id
            } else {
                this.listQuery.user_id = 0
            }
        },
        handleSelectionChange(val) {
            let ids = []
            val.forEach(element => {
                if (ids.indexOf(element.id) == -1) {
                    ids.push(element.id)
                }
            })
            this.multSelected = ids.join()
        },
        onSendCancel() {
            this.etype = []
            this.isShow = false
        },
        onMultiSend() {
            if (this.multSelected.length > 0) {
                if (!confirm(i18n.t('categoryfile.confirm') + '?')) {
                    return false;
                }
                let _this = this
                let params = {
                    order_id: this.multSelected,
                    etype: this.multiEtype.join()
                }
                if (this.multiEtype.length > 0) {
                    _this.isShow = false
                    fetchOrderEmail(this.multSelected, params).then(() => {
                        _this.multiEtype = []
                        _this.$notify({
                            title: 'Message',
                            message: 'Success！',
                            type: 'success',
                            duration: 2000
                        })
                    })
                } else {
                    this.$message.error('Please Select E-mail Type')
                }
            } else {
                this.$message.error('Choose at least one order')
            }
        },
        onMultiOrderResume() {
            let _this = this
            if(this.multSelected.length > 0) {
                if (!confirm(i18n.t('categoryfile.confirm') + '?')) {
                    return false;
                }
                fetchResume(this.multSelected).then(() => {
                    _this.getList()       
                    this.$notify({
                        title: 'Message',
                        message: 'Success！',
                        type: 'success',
                        duration: 2000
                    })
                })
            } else {
                this.$message.error('Choose at least one order')
            }
        },
        onMultiOrderHold() {
            let _this = this
            if (this.multSelected.length > 0) {
                if (!confirm(i18n.t('categoryfile.confirm') + '?')) {
                    return false;
                }
                fetchHold(this.multSelected).then(() => {
                    _this.getList()
                    this.$notify({
                        title: 'Message',
                        message: 'Success！',
                        type: 'success',
                        duration: 2000
                    })
                })
            } else {
                this.$message.error('Choose at least one order')
            }
        },
        onMultiOrderVoid() {
            let _this = this
            if (this.multSelected.length > 0) {
                if (!confirm(i18n.t('categoryfile.confirm') + '?')) {
                    return false;
                }
                fetchOrderVoid(this.multSelected).then(() => {
                    _this.getList()
                    this.$notify({
                        title: 'Message',
                        message: 'Success！',
                        type: 'success',
                        duration: 2000
                    })
                })
            } else {
                this.$message.error('Choose at least one order')
            }
        },
        changeAssemble(index, data) {
            // this.orderData.assemble[index] = data
            this.assembles[index] = data
            this.getTotal()
            this.getBalance(this.orderData.payment)
        },
        handleClose() {
            this.resetTemp()
            this.showButton = false
            this.dialogFormVisible = false
        },
        searchSyncAx() { // 批量处理数据
            // 搜索
            let _this = this
            if (this.syncForm.delivery_date) {
                this.syncForm.delivery_start_date = formatData(this.syncForm.delivery_date[0]).substr(0, 10)
                this.syncForm.delivery_end_date = formatData(this.syncForm.delivery_date[1]).substr(0, 10)
            }
            fetchSyncAx(this.syncForm).then((res) => {
                let data = res.data
                _this.order_items = data
                let ids = []
                data.forEach(ele => {
                    ids.push(ele.order_id)
                })
                _this.order_ids = ids
                _this.ax_delivery_start_date = this.syncForm.delivery_start_date
                _this.ax_delivery_end_date = this.syncForm.delivery_end_date

                /* this.$notify({
                    title: 'Success',
                    message: 'Successful operation',
                    type: 'success',
                    duration: 2000
                }) */
            })
        },
        sendSyncAx() { // 提交接口
            let _this = this
            if (this.order_ids.length > 0) {
                let postData = {
                    order_ids: this.order_ids, // 多个订单ids
                    ax_sync_item_status: 0,
                    ax_sync_type: 2, // type:1 单个订单 type:2多个订单
                    // order_no: 123, // 单个订单id
                    region_code: 'HK',
                    ax_delivery_start_date: this.ax_delivery_start_date,
                    ax_delivery_end_date: this.ax_delivery_end_date
                }
                fetchPostSyncAx(postData).then((res) => {
                    if(res.data.success){
                        _this.syncAxVisible = false
                        _this.$notify({
                            title: 'Success',
                            message: 'Success!',
                            type: 'success',
                            duration: 2000
                        })
                        _this.order_items = [];
                    }else{
                        this.$message.error(res.data.failedMessage);
                    }
                })
            } else {
                this.$message.error('Please select order!');
            }
        }
        /* updateOrderRemark(index) {// 修改订单备注
            if (this.item.remark) {
                let data = {
                    id: this.item.id,
                    remark: this.item.remark
                }
                fetchUpdateRemark(this.item.id, data).then(() => {
                    this.$notify({
                        title: 'Success',
                        message: 'Update Success!',
                        type: 'success',
                        duration: 2000
                    })
                })
            }

        },
        updateOrderPaymentRemark(index) {// 修改订单备注
            if (this.item.paymentRemark) {
                let data = {
                    id: this.item.id,
                    remark: this.item.paymentRemark
                }
                fetchUpdatePaymentRemark(this.item.id, data).then(() => {
                    this.$notify({
                        title: 'Success',
                        message: 'Update Success!',
                        type: 'success',
                        duration: 2000
                    })
                })
            }

        },
        updateOrderHold(id) {// 暂停订单
            fetchHold(id).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Successful operation',
                    type: 'success',
                    duration: 2000
                })
            })
        },
        updateOrderResume(id) {// 继续订单
            fetchResume(id).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Successful operation',
                    type: 'success',
                    duration: 2000
                })
            })
        },
        updateOrderVoid(id) {// 无效订单
            fetchOrderVoid(id).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Successful operation',
                    type: 'success',
                    duration: 2000
                })
            })
        },
        onSendCancel() {
            this.etype = []
            this.isShow = false
        },
        onSend(item) {
            let _this = this
            let params = {
                id: item.id,
                etype: this.etype.join()
            }
            if (this.etype) {
                fetchOrderEmail(item.id, params).then(() => {
                    _this.etype = []
                    _this.$notify({
                        title: 'Success',
                        message: 'Successful operation',
                        type: 'success',
                        duration: 2000
                    })
                    _this.isShow = false
                })
            }
        } */
    }
}
</script>
<style rel="stylesheet/scss" lang="scss">
    @import "src/styles/mixin.scss";
    .orderList{
        .filter-container{
            padding: 20px 10px 10px;
            background-color: #f1f1f1;
            margin-bottom: 10px;
            .button-box{
                text-align: left
            }
        }
    }
    .email-box{
        line-height: 22px;
        .el-checkbox-group{
            margin-top: 10px;   
            margin-bottom: 10px;
            .el-checkbox{
                margin-left: 30px;
            }
        }
    }
    .filter-container .el-form-item--medium .el-form-item__content, .filter-container .el-form-item--medium .el-form-item__label{ line-height: 16px;}
    .ref-form{font-size: 16px; height: 45px; font-weight: bold;}
    .button-box{margin-left: 20px; text-align: right;}
    .order-list-box{
        .border-none.el-row{ border:none;}
        .el-form-item{ margin-bottom: 0;}
        .el-row {
            margin-bottom: 20px;
            border-bottom: 1px solid #e5e9f2;
            border-right: 1px solid #e5e9f2;
            /* &:last-child {
                margin-bottom: 0;
            } */
        }
        .left-text {
            line-height: 30px;
        }
        .grid-content {
            padding: 5px;
            line-height: 20px;
            min-height: 36px;
            border-left: 1px solid #e5e9f2;
            border-top: 1px solid #e5e9f2;
        }
        .bg-grey-light{ text-align: right; background: #e5e9f2;}
        .center{ text-align: center;}
        .f-red{ color: #f00;}
        .f-green{ color: #67C23A;}
    }
    .order-product-container{

        .order-product-hd{
            height: 40px;
            padding: 5px;
            background: #409eff;
            .y-label{
                color: #fff;
            }
        }
        .order-product-main{
            margin-top:10px;
            line-height: 20px;
            font-size: 12px;
        }
        .text-right{ text-align:  right;}
    }
    .order-footer-box{ margin-top: 20px;}
    .order-group-products{
        .grid-content{
                height: 235px;
                border-left: 1px solid #e5e9f2;
                border-top: 1px solid #e5e9f2;
        }
        .ch-first{
            height: 25px;
            line-height: 25px;
            border-top: none;
        }
    }
    .payment-box{
        .item{
            display: inline-block;
            width: 100px;
        }
    }
    .orders-row{
        .bg-grey-light{ text-align: center; background: #e5e9f2;}
    }
</style>
